import warningCounts from '../server/helpers/warningCounts';
import initServerInstance from '../server/initServerInstance';

if (require.main === module) {
	(async () => {
		const server = await initServerInstance({
			loggerConfig: {
				name: 'upgrade',
				alwaysCreate: true,
			},
		});

		for await (const record of server.app.model.Task.find()) {
			Object.assign(record.result, warningCounts(record.result.warnings));
			if (record.taskType === 'asset') {
				record.result.stats = {
					subdomainCount: 0,
					ipCount: 0,
					portCount: 0,
					ipBindDomainCount: 0,
					addSubdomainCount: 0,
					addIpCount: 0,
					addPortCount: 0,
					addIpBindDomainCount: 0,
					removeSubdomainCount: 0,
					removeIpCount: 0,
					removePortCount: 0,
					removeIpBindDomainCount: 0,
					changePortServiceCount: 0,
				};
				record.result.stats.subdomainCount = record.result.subDomains.length;
				record.result.stats.ipCount = record.result.ipPorts.length;
				record.result.stats.portCount = record.result.ipPorts.reduce(
					(count, x) => count + x.ports?.length || 0,
					0
				);
				record.result.stats.ipBindDomainCount = record.result.ipBindDomains.reduce(
					(set, record) => {
						set.add(...record.domains.forEach(x => set.add(x.domain)));
						return set;
					},
					new Set()
				).size;
				record.result.warnings.reduce((obj, x) => {
					let key;
					if (x.category === 'portService') {
						key = 'changePortServiceCount';
					} else {
						const category = x.category[0].toUpperCase() + x.category.slice(1);
						const op = x.detail.op;
						key = `${op}${category}Count`;
					}
					obj[key] += 1;

					return obj;
				}, record.result.stats);
			}
			await record.save();
		}

		process.exit();
	})();
}
